<?php
defined('APP_PATH') or die ('Unauthorized access');
/**
 * 缓存核心库
 * @author windpurple
 * @version 1.0
 */
final class Cache
{
	private $_cachefile;
	public $lifetime;
	static private $_instance = NULL;
	
	private function __construct()
	{
		
	}
	
	private function __clone()
	{
		
	}
	
	static public function getInstance()
	{
		if(is_null(self::$_instance) || !isset(self::$_instance)){
			self::$_instance = new Cache();
		}
		return self::$_instance;
	}
	
	/**
	 * 验证数据缓存
	 * @param unknown_type $key
	 */
	public function check($key)
	{
		$this->getCacheFile($key);

		if(file_exists($this->_cachefile)){
			return filectime($this->_cachefile) < time() - $this->lifetime ? false : true;
		}else{
			return false;
		}
		
	}
	
	/**
	 * 保存缓存数据
	 * @param unknown_type $key
	 * @param unknown_type $data
	 */
	public function save($key,$data = array())
	{
		$this->getCacheFile($key);
		$data = serialize($data);
		$file = fopen($this->_cachefile,'w');
		fwrite($file,$data);
		//chmod($this->_cachefile,0777);
		fclose($file);
		return 1;
		
	}
	
	public function load($key)
	{
		$this->getCacheFile($key);
		$data = file_get_contents($this->_cachefile);
		return unserialize(stripslashes($data));
	}
	
	private function getCacheFile($key)
	{
		$key = strtoupper(md5(md5($key)));
		global $config;
		$this->_cachefile = APP_PATH.'/'.$config['cache_dir'].'/'.$key.'.'.$config['cache_suffix'];
	}
	
}